import {ref, computed, watch} from 'vue';
import { defineStore } from 'pinia';
import { getCityByName, getWeatherByAdcode } from '@/api/city.js' // 引入数据接口


const FORECAST_LOCAL_KEY = 'weather_forecast_local'
const FORECAST_SEARCH_KEY = 'weather_forecast_search'
const CURRENT_SEARCH_KEY = 'weather_current_search'
const CITY_LIST_KEY = 'city_list'

// 使用 defineStore 定义 store：
export const useWeatherStore = defineStore('weather', () => {

  //当地城市 的 预测天气 
  const forecastLocalCity = ref(JSON.parse(localStorage.getItem(FORECAST_LOCAL_KEY) || 'null')) // 初始化时尝试从localStorage恢复  刷新页面，数据不丢失
  function setForecastLocalCity(data) {
    forecastLocalCity.value = data
    localStorage.setItem(FORECAST_LOCAL_KEY, JSON.stringify(data))
  }

  // 查询城市 的 当前天气
  const currentSearchCity = ref(JSON.parse(localStorage.getItem(CURRENT_SEARCH_KEY) || 'null'))
  function setCurrentSearchCity(data) {
    currentSearchCity.value = data
    localStorage.setItem(CURRENT_SEARCH_KEY, JSON.stringify(data))
  }

  // 查询城市 的 预测天气
  const forecastSearchCity = ref(JSON.parse(localStorage.getItem(FORECAST_SEARCH_KEY) || 'null')) 
  function setForecastSearchCity(data) {
    forecastSearchCity.value = data
    localStorage.setItem(FORECAST_SEARCH_KEY, JSON.stringify(data))
  }

  return { forecastLocalCity, setForecastLocalCity, currentSearchCity, setCurrentSearchCity, forecastSearchCity, setForecastSearchCity }
})


export const useCityListStore = defineStore('cityList', () => {
  const cityList = ref(JSON.parse(localStorage.getItem(CITY_LIST_KEY) || '[]')) // 城市列表初始化时尝试从localStorage恢复  [{name: xx市, temperature: xx}, ...]

  // 持久化 深度监听数组内部的增删改
  watch((cityList), (newList) => {
    localStorage.setItem(CITY_LIST_KEY, JSON.stringify(newList))  
    console.log('正在监听')
  }, { deep: true })

  function setCityList(data) {
    cityList.value = data
  }
  function pushCity(city) {
    cityList.value.push(city)
  }
  function removeCity(index) {
    cityList.value.splice(index, 1)
  }

  // 添加城市（内部请求真实温度）
  function findIndex(name) {
    return cityList.value.findIndex(c => c.name === name)
  }
  // name城市名称，presetTemperature预设温度（可选）
  async function addCity(name, presetTemperature) {
    if (!name) return
    if (findIndex(name) !== -1) return // 已存在
    // 先插入占位
    cityList.value.push({
      name,
      temperature: presetTemperature ?? '--',
    })
    // 获取adcode
    const data = await getCityByName(name)
    const adcode = data.geocodes[0].adcode
    // 当前天气
    const Current = await getWeatherByAdcode(adcode,)
    const temp = Current.lives[0].temperature
    // 回填列表
    const idx = findIndex(name)
    if (idx !== -1) {
      cityList.value[idx].temperature = temp
    }
  }

  return { cityList, setCityList, pushCity, removeCity, addCity }
})